import 'dart:convert';
import 'package:dio/dio.dart' as dio; //接口请求库
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:fluttertoast/fluttertoast.dart'; //提示框
import 'package:jovial_svg/jovial_svg.dart'; //svg
import 'package:flutter_svg/flutter_svg.dart'; //svg
// import 'package:flutter_bmflocation/flutter_bmflocation.dart';

import 'dart:ui'; // 用于矩阵变换相关操作
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';
import 'package:vector_math/vector_math_64.dart'
    as vector_math; // 为 vector_math 指定别名
//气泡框组件
import 'tooltip_widget.dart';
//提示框组件
import 'toast_utils.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:shared_preferences/shared_preferences.dart';

import './page/login/login_page.dart'; // 引入登录页面
import 'package:rjpb/page/home/home_page.dart';
import './page/login/apis/login_api.dart'; // 引入提取的 AuthService
import 'package:get/get.dart';
import 'package:rjpb/routes/route.dart';
import 'package:rjpb/page/login/apis/auth_service.dart';
import 'package:rjpb/shared/utils/storage_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:rjpb/page/home/fireAlarmAlert/controller/fire_alarm_alert_controller.dart';
import 'package:rjpb/page/home/fireAlarm/controller/fireAlarm_page_controller.dart';
import 'dart:isolate'; // 用于 SendPort 类型
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter/services.dart';
import 'package:get_storage/get_storage.dart';
import 'package:flutter/foundation.dart'; // compute 函数
import 'dart:async'; // 导入 unawaited 所在的库

const String isolateName = 'websocket_keep_alive_port';

void registerReceivePort() {
  final receivePort = ReceivePort();
  IsolateNameServer.registerPortWithName(receivePort.sendPort, isolateName);

  receivePort.listen((message) {
    if (message == 'ping') {
      print('[调试] 收到后台服务的 ping 指令，执行 WebSocket 保活');
      // 手动调用 WebSocket 重连或心跳逻辑
      final controller = Get.find<FireAlarmPageController>();
      controller.reconnectWebSocketIfNeeded();
    }
  });
}

class MyTaskHandler extends TaskHandler {
  SendPort? _sendPort;
  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {
    _sendPort = IsolateNameServer.lookupPortByName(isolateName);
    print('[前台服务] 启动');
  }

  @override
  Future<void> onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {
    print('[前台服务] 保活中...');
    // 此处不能直接访问 Controller（因运行在 isolate），可考虑使用本地缓存/HTTP Ping 等方式保活
    _sendPort ??= IsolateNameServer.lookupPortByName(isolateName);
    _sendPort?.send('ping'); // 向主 isolate 发送保活指令
  }

  @override
  Future<void> onDestroy(DateTime timestamp, SendPort? sendPort) async {
    print('[前台服务] 已销毁');
  }

  @override
  void onNotificationButtonPressed(String id) {}

  @override
  void onNotificationPressed() {}
}

void initForegroundTask() {
  FlutterForegroundTask.init(
    androidNotificationOptions: AndroidNotificationOptions(
      channelId: 'fire_alarm_channel',
      channelName: '火警前台服务',
      channelDescription: '保持 WebSocket 长连接',
      channelImportance: NotificationChannelImportance.LOW,
      priority: NotificationPriority.LOW,
      iconData: const NotificationIconData(
        resType: ResourceType.mipmap,
        resPrefix: ResourcePrefix.ic,
        name: 'launcher',
      ),
      buttons: [const NotificationButton(id: 'stop', text: '停止')],
    ),
    iosNotificationOptions: const IOSNotificationOptions(
      showNotification: true,
      playSound: false,
    ),
    foregroundTaskOptions: const ForegroundTaskOptions(
      interval: 5000,
      isOnceEvent: false,
      allowWakeLock: true,
      allowWifiLock: true,
      autoRunOnBoot: true,
    ),
  );
}

Future<void> startForegroundService() async {
  print('[调试] 尝试启动前台服务...');
  await FlutterForegroundTask.stopService(); // 保证旧服务被停止
  final started = await FlutterForegroundTask.startService(
    notificationTitle: '火警监听中',
    notificationText: '正在实时接收火警信息...',
    // callback: () {
    //   FlutterForegroundTask.setTaskHandler(MyTaskHandler());
    // },
    callback: startCallback,
  );

  print('[前台服务] 启动结果: $started');
}

void startCallback() {
  print('[调试] startCallback 被调用了');
  FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await GetStorage.init(); // 初始化 GetStorage
  registerReceivePort(); // 注册接收端口

  initForegroundTask(); // ✅ 必须加 await
  await startForegroundService(); // ✅ 启动服务
  // await FlutterForegroundTask.stopService();
  // await FlutterForegroundTask.startService(
  //   notificationTitle: '火警监听中',
  //   notificationText: '正在实时接收火警信息...',
  //   callback: startCallback, // ✅ 正确使用函数名
  // );
  await StorageUtil.init(); // 初始化 StorageUtil
  await initServices(); // 初始化 GetX Controller

  final token = await StorageUtil.getToken();
  final isTokenExpired = await AuthService.isTokenExpired();
  // 启动预加载（不阻塞主线程）
  unawaited(_preloadData());
  runApp(
    ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_, child) {
        return MyApp(
            isLoggedIn: token != null && token.isNotEmpty && !isTokenExpired);
      },
    ),
  );
}

// 预加载关键数据
// 主isolate预加载方法
Future<void> _preloadData() async {
  try {
    print('🚀 开始预加载...');
    final stopwatch = Stopwatch()..start();

    final controller = Get.find<FireAlarmPageController>();
    await controller.preloadCommonSvgs();

    print('预加载完成，耗时 ${stopwatch.elapsedMilliseconds}ms');
  } catch (e) {
    print('预加载失败: $e');
  }
}

// 初始化GetX服务
Future<void> initServices() async {
  await Get.putAsync(() => SharedPreferences.getInstance());
  Get.put(FireAlarmAlertController());
  Get.put(FireAlarmPageController());
  // 其他需要初始化的服务...
}

class MyApp extends StatelessWidget {
  final bool isLoggedIn;

  MyApp({required this.isLoggedIn});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: '登录页面',
      theme: ThemeData(primarySwatch: Colors.blue),
      initialRoute: isLoggedIn ? '/home' : '/login',
      getPages: [
        GetPage(name: '/login', page: () => LoginPage()),
        GetPage(name: '/home', page: () => HomePage()),
      ],
    );
  }
}
